let startTime = null

// 初始化时间
function initStartTime() {
  startTime = null
}

// 格式化时间戳
function getTime({
  timer = null,
  type = null,
  interval = '/'
} = {}) {
  const time = timer ? new Date(timer) : new Date()
  const year = time.getFullYear()
  const month = dblString(time.getMonth() + 1)
  const day = dblString(time.getDate())
  const hours = dblString(time.getHours())
  const min = dblString(time.getMinutes())
  const sec = dblString(time.getSeconds())
  let timereturn = ''
  switch (type) {
    case 0:
      timereturn = `${year}${interval}${month}${interval}${day} 00:00:00`
      break
    case 1 :
      timereturn = `${year}${interval}${month}${interval}${day} ${hours}:${min}`
      break
    case 2 :
      timereturn = `${year}${interval}${month}${interval}${day}`
      break
    case 3 :
      timereturn = `${hours}:${min}:${sec}`
      break
    case 4 :
      timereturn = `${hours}:${min}`
      break
    default :
      timereturn = `${year}${interval}${month}${interval}${day} ${hours}:${min}:${sec}`
  }
  return timereturn
}

// 补0
function dblString(n) {
  n = n + ''
  if (n.length < 2) {
    return `0${n}`
  } else {
    return n
  }
}

// 显示时间处理
function getTimeChange(timer) {
  const todayZeroTimer = new Date(getTime({ type: 0 })).getTime() // 今日零时的时间戳
  const currentTime = new Date(timer).getTime()
  const timeInterval = 24 * 60 * 60 * 1000
  if (currentTime > todayZeroTimer) { // 今天的时间
    return getTime({ timer: timer, type: 4 })
  } else if (todayZeroTimer - currentTime < timeInterval) { // 昨天时间
    return `昨天 ${getTime({ timer: timer, type: 4 })}`
  } else {
    return `${getTime({ timer: timer, type: 1 })}`
  }
}

// 设置需要显示的时间
function showTimer(timer) {
  if (!startTime) {
    startTime = timer
    return getTimeChange(timer)
  } else {
    const timeInterval = 2 * 60 * 1000
    if (Math.abs(new Date(timer).getTime() - new Date(startTime).getTime()) > timeInterval) {
      startTime = timer
      return getTimeChange(timer)
    } else {
      return null
    }
  }
}

export  {
  showTimer,
  initStartTime
}
